package com.roger.homecenterscreen.voice

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat

/**
 * 语音功能权限检查助手
 * 根据讯飞AIKit官方文档要求进行权限验证
 */
object VoicePermissionHelper {
    private const val TAG = "VoicePermissionHelper"
    
    /**
     * AIKit必需的权限列表
     */
    private val REQUIRED_PERMISSIONS: List<String> = listOf(
        Manifest.permission.RECORD_AUDIO,           // 录音权限
        Manifest.permission.INTERNET,               // 网络权限（激活需要）
        Manifest.permission.READ_PHONE_STATE,       // 设备信息权限
        Manifest.permission.WRITE_EXTERNAL_STORAGE, // 写存储权限
        Manifest.permission.READ_EXTERNAL_STORAGE,  // 读存储权限
        Manifest.permission.MODIFY_AUDIO_SETTINGS   // 音频设置权限
    )
    
    /**
     * Android 10+需要的额外权限
     */
    private val ANDROID_10_PLUS_PERMISSIONS: List<String> = listOf(
        "android.permission.READ_PRIVILEGED_PHONE_STATE"  // 使用字符串形式避免API兼容性问题
    )
    
    /**
     * Android 11+需要的额外权限
     */
    private val ANDROID_11_PLUS_PERMISSIONS: List<String> = listOf(
        Manifest.permission.MANAGE_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_NUMBERS
    )
    
    /**
     * 检查所有必需的权限
     */
    fun checkAllPermissions(context: Context): Boolean {
        Log.i(TAG, "🔐 开始检查AIKit所需权限...")
        
        val missingPermissions = mutableListOf<String>()
        
        // 检查基础权限
        for (permission in REQUIRED_PERMISSIONS) {
            if (!isPermissionGranted(context, permission)) {
                missingPermissions.add(permission)
                Log.w(TAG, "❌ 缺少权限: $permission")
            } else {
                Log.d(TAG, "✅ 权限已授予: $permission")
            }
        }
        
        // 检查Android版本特定权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            for (permission in ANDROID_10_PLUS_PERMISSIONS) {
                if (!isPermissionGranted(context, permission)) {
                    missingPermissions.add(permission)
                    Log.w(TAG, "❌ 缺少Android 10+权限: $permission")
                }
            }
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            for (permission in ANDROID_11_PLUS_PERMISSIONS) {
                if (!isPermissionGranted(context, permission)) {
                    missingPermissions.add(permission)
                    Log.w(TAG, "❌ 缺少Android 11+权限: $permission")
                }
            }
        }
        
        return if (missingPermissions.isEmpty()) {
            Log.i(TAG, "✅ 所有AIKit必需权限已授予")
            true
        } else {
            Log.e(TAG, "❌ 缺少${missingPermissions.size}个必需权限")
            Log.e(TAG, "💡 请在设置中手动授予这些权限后重启应用")
            false
        }
    }
    
    /**
     * 检查录音权限（最关键）
     */
    fun checkRecordAudioPermission(context: Context): Boolean {
        val granted = isPermissionGranted(context, Manifest.permission.RECORD_AUDIO)
        if (!granted) {
            Log.e(TAG, "❌ 录音权限未授予，语音功能无法使用")
            Log.e(TAG, "💡 请在设置 -> 应用权限 -> 麦克风中授予权限")
        }
        return granted
    }
    
    /**
     * 检查网络权限（激活需要）
     */
    fun checkNetworkPermission(context: Context): Boolean {
        val granted = isPermissionGranted(context, Manifest.permission.INTERNET)
        if (!granted) {
            Log.e(TAG, "❌ 网络权限未授予，无法在线激活AIKit")
        }
        return granted
    }
    
    /**
     * 生成权限诊断报告
     */
    fun generatePermissionReport(context: Context): String {
        val report = StringBuilder()
        report.appendLine("=== AIKit权限诊断报告 ===")
        report.appendLine("设备信息:")
        report.appendLine("  - Android版本: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")
        report.appendLine("  - 设备型号: ${Build.MODEL}")
        report.appendLine("  - 制造商: ${Build.MANUFACTURER}")
        report.appendLine()
        
        report.appendLine("基础权限:")
        for (permission in REQUIRED_PERMISSIONS) {
            val status = if (isPermissionGranted(context, permission)) "✅" else "❌"
            report.appendLine("  $status ${getPermissionName(permission)}")
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            report.appendLine("Android 10+权限:")
            for (permission in ANDROID_10_PLUS_PERMISSIONS) {
                val status = if (isPermissionGranted(context, permission)) "✅" else "❌"
                report.appendLine("  $status ${getPermissionName(permission)}")
            }
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            report.appendLine("Android 11+权限:")
            for (permission in ANDROID_11_PLUS_PERMISSIONS) {
                val status = if (isPermissionGranted(context, permission)) "✅" else "❌"
                report.appendLine("  $status ${getPermissionName(permission)}")
            }
        }
        
        return report.toString()
    }
    
    private fun isPermissionGranted(context: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
    }
    
    private fun getPermissionName(permission: String): String {
        return when (permission) {
            Manifest.permission.RECORD_AUDIO -> "录音权限"
            Manifest.permission.INTERNET -> "网络权限"
            Manifest.permission.READ_PHONE_STATE -> "设备信息权限"
            Manifest.permission.WRITE_EXTERNAL_STORAGE -> "写存储权限"
            Manifest.permission.READ_EXTERNAL_STORAGE -> "读存储权限"
            Manifest.permission.MODIFY_AUDIO_SETTINGS -> "音频设置权限"
            "android.permission.READ_PRIVILEGED_PHONE_STATE" -> "特权设备信息权限"
            Manifest.permission.MANAGE_EXTERNAL_STORAGE -> "管理存储权限"
            Manifest.permission.READ_PHONE_NUMBERS -> "读取电话号码权限"
            else -> permission
        }
    }
}